package com.ihome.excel.xlsx.engine.export;

import java.lang.reflect.Method;
import java.util.List;

import com.ihome.excel.xlsx.entity.EncapsulationEnum;
import com.ihome.excel.xlsx.entity.ExcelRule;
import com.ihome.excel.xlsx.exceptions.ExcelRuleValidateException;
import com.ihome.excel.xlsx.exceptions.ThrowableDefine;

public class ExcelRuleValidate {
	
	private static final String GET = "get";

	public void checkExcelRule(ExcelRule excelRule) throws ExcelRuleValidateException{
		if(excelRule == null) {
			throw ThrowableDefine.PARAMETER_VALIDATE_EXP.getIllegaArgumentExp("excelRule");
		}
		if(excelRule.getRuleName() == null || "".equals(excelRule.getRuleName())) {
			throw ThrowableDefine.EXCEL_RULE_VALIDATE_ERROR.getExcelRuleValidateExp("规则名称ruleName");			
		}
		if(excelRule.getExcelName() == null || "".equals(excelRule.getExcelName())) {
			throw ThrowableDefine.EXCEL_RULE_VALIDATE_ERROR.getExcelRuleValidateExp("生成的文件名称excelName");
		}
		if(excelRule.getSheetName() == null || "".equals(excelRule.getSheetName())) {
			throw ThrowableDefine.EXCEL_RULE_VALIDATE_ERROR.getExcelRuleValidateExp("sheet名称sheetName");
		}
		String className = excelRule.getClassName();
		if(className == null || "".equals(className)) {
			throw ThrowableDefine.EXCEL_RULE_VALIDATE_ERROR.getExcelRuleValidateExp("映射对象className");
		}
		if(!EncapsulationEnum.MAP.toString().equals(className)) {
			Class classz = null;
			try {
				classz = Class.forName(className);
			} catch (ClassNotFoundException e) {
				throw ThrowableDefine.EXCEL_RULE_MAPPING_EROOR.getExcelRuleValidateExp(e.getMessage());
			}
			List<String> valueAttribute = excelRule.getColumnAttributeNameConfig();
			String methodName = null;
			Method[] methods = classz.getDeclaredMethods();
			boolean isExists;
			for(String att : valueAttribute) {
				isExists = false;
				methodName = GET + att.substring(0, 1).toUpperCase() + att.substring(1, att.length());
				for(Method method : methods) {
					if(method.getName().equals(methodName)) {
						isExists = true;
						break;
					}
				}
				if(!isExists) {
					throw ThrowableDefine.EXCEL_RULE_ATTRIBUTE_ERROR.getExcelRuleValidateExp(att,className);
				}
			}
		}	
	}
}
